package com.easy.oss.service;

import com.easy.framework.common.utils.AssertUtil;
import com.easy.framework.common.utils.Func;
import com.easy.framework.database.page.PageUtil;
import com.easy.framework.database.page.Pagination;
import com.easy.oss.model.query.ItemQuery;
import com.easy.oss.model.vo.BucketVO;
import com.easy.oss.model.vo.ItemVO;
import io.minio.ListObjectsArgs;
import io.minio.MinioClient;
import io.minio.RemoveObjectArgs;
import io.minio.Result;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@RequiredArgsConstructor
public class MinioService {


    final EasyMinioClient easyMinioClient;

    public List<BucketVO> getBucketList(){
        List<BucketVO> list = new ArrayList<>();
        try {
            List<Bucket> bucketList = easyMinioClient.listBuckets();
            for (Bucket bucket : bucketList) {

                list.add(new BucketVO(bucket.name(), Date.from(bucket.creationDate().toInstant())));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public Pagination<ItemVO> getItemList(String bucketName, ItemQuery query) {
        AssertUtil.isTrue(Func.isNotEmpty(bucketName), "参数错误");
        ListObjectsArgs.Builder args=ListObjectsArgs.builder().bucket(bucketName);
        if (Func.isNotEmpty(query.getDir())) {
            args.prefix(query.getDir());
        }
        Iterable<Result<Item>> iterable = easyMinioClient.listObjects(args.build());
        List<ItemVO> list = new ArrayList<>();
        if (Func.isNotEmpty(iterable)) {
            iterable.forEach(p -> {
                try {
                    list.add(new ItemVO(p.get()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return PageUtil.page(query.getPageNum(), query.getPageSize(), list);
    }


    /**
     * 删除
     * @param bucketName
     * @param fileNameList
     * @return
     */
    public boolean remove(String bucketName, List<String> fileNameList) {
        if(Func.isNotEmpty(fileNameList)){
            for (String fileName:fileNameList) {
                try {
                    easyMinioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return true;
        }
        return false;
    }

}
